<?php
class PicturesController extends AppController {
	var $name = 'Pictures';

	function admin_index() {
		$this->set('pictures', $this->Picture->findAll(null, array('picture_id')));
	}

	function admin_view($pictureId = null) {
		$this->view($pictureId);
	}

	function admin_rotate($pictureId = null, $degree = null) {
		if ($pictureId == null) {
			$this->Session->setFlash('invalid picture id');
			$this->redirect('/admin/pictures/');
			return;
		}

		if ($degree == null) {
			$this->Session->setFlash('invalid degree');
			$this->redirect('/admin/pictures/');
			return;
		}

		$picture = $this->Picture->read(null, $pictureId);
		$source = imagecreatefromstring($picture['Picture']['picture']);

		$rotate = imagerotate($source, 90, 0);

		ob_start();
		imagejpeg($rotate);
		$image = ob_get_contents();
		ob_end_clean();

		$picture['Picture']['picture'] = $image;

		$this->Picture->save($picture);

		$this->redirect($this->referer());
	}

	function admin_delete($pictureId = null) {
		if ($pictureId == null) {
			$this->Session->setFlash('invalid picture id');
			$this->redirect($html->referer());
			return;
		}

		if ($this->Picture->del($pictureId)) {
			$this->Session->setFlash('The picture was deleted: id '.$pictureId);
			$this->redirect($html->referer());
		}
	}

	function admin_edit($pictureId = null) {
		$this->set('pictureId', $pictureId);
		$actionList = array('rotate' => 'Rotate');
		$this->set('actionList', $actionList);

		if (empty($this->data)) {
			if (!$pictureId) {
				$this->Session->setFlash('Invalid id for picture');
				$this->redirect('/admin/users');
			}
		} else {
			$this->cleanUpFields();
			if ($this->Apartment->save($this->data)) {
				$this->Session->setFlash('The Apartment has been saved');
				$this->redirect('/admin/apartments');
			} else {
				$this->Session->setFlash('Please correct errors below.');
			}
		}
	}

	function view($pictureId) {
		if ($pictureId == null) {
			return;
		}
		$picture = $this->Picture->findByPictureId($pictureId);
		$this->layout = "jpg";
		$this->set('picture', $picture);
	}
}
?>
